/*
 * Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.huawei.cloudphone.virtualdevice.common;

import java.util.Arrays;

public class RingBuffer<T> {
    private final static int DEFAULT_SIZE = 1024;
    private Object[] buffer;
    private int head = 0;
    private int tail = 0;
    private int bufferSize;

    public RingBuffer() {
        this.bufferSize = DEFAULT_SIZE;
        this.buffer = new Object[bufferSize];
    }

    public RingBuffer(int size) {
        this.bufferSize = size;
        this.buffer = new Object[bufferSize];
    }

    private Boolean isEmpty() {
        return head == tail;
    }

    private Boolean isFull() {
        return (tail + 1) % bufferSize == head;
    }

    public void clear() {
        Arrays.fill(buffer, null);
        this.head = 0;
        this.tail = 0;
    }

    public Boolean put(Object v) {
        if (isFull()) {
            return false;
        }
        buffer[tail] = v;
        tail = (tail + 1) % bufferSize;
        return true;
    }

    public Object get() {
        if (isEmpty()) {
            return null;
        }
        Object result = buffer[head];
        head = (head + 1) % bufferSize;
        return result;
    }

    public Object[] getAll() {
        if (isEmpty()) {
            return new Object[0];
        }
        int copyTail = tail;
        int count = head < copyTail ? copyTail - head : bufferSize - head + copyTail;
        Object[] result = new String[count];
        if (head < copyTail) {
            if (copyTail - head >= 0)
                System.arraycopy(buffer, head, result, 0, copyTail - head);
        } else {
            if (bufferSize - head >= 0)
                System.arraycopy(buffer, head, result, 0, bufferSize - head);
            if (copyTail >= 0) System.arraycopy(buffer, 0, result, bufferSize - head, copyTail);
        }
        head = copyTail;
        return result;
    }
}
